
import 'package:boss/main.dart';
import 'package:boss/models/offers.dart';
import 'package:boss/ui/page/offersManagement/constant/offers_constant.dart';
import 'package:boss/ui/page/offersManagement/page/plusOffersMode/page/fullOffers/model/full_rule_data.dart';
import 'package:boss/ui/page/offersManagement/page/plusOffersMode/page/provider/base_provider.dart';
import 'package:boss/ui/widget/loading/loading.dart';
import 'package:hi_common/hi_common.dart';

class FullOffersProvider extends BaseProvider {
  FullOffersProvider({Offers data}) {
    super.initData(data: data);
    if (data != null) {
      rules = [];
      data.fullDiscountList.forEach((item) {
        rules.add(FullRuleData(
          full: AmountUtil.price2String(item.fullCount),
          less: AmountUtil.price2String(item.reductionCount),
        ));
      });
    }
  }

  List<FullRuleData> rules = [
    FullRuleData(),
  ];

  addRule() {
    rules.add(FullRuleData());
    notifyListeners();
  }

  removeRule(FullRuleData value) {
    rules.remove(value);
    notifyListeners();
  }

  Future<bool> addFullOffers() async {
    try {
      if (offerName == null || offerName == '') {
        toast('请填写优惠名称');
        return false;
      }

      if (!rules.every((item) => item.full != '' && item.less != '')) {
        toast('满减规则请填写完整');
        return false;
      }

      List<Map<String, dynamic>> listFullDiscount = rules
          .map((item) => {
                'discountName': offerName,
                'fullCount': AmountUtil.string2Price(item.full),
                'reductionCount': AmountUtil.string2Price(item.less),
              })
          .toList();

      showLoadingToast();

      Map<String, dynamic> data = {
        'listFullDiscount': listFullDiscount,
        'storeDiscountStandard': {
          'activityName': offerName,
          'activityType': activityType,
          'discountType': OffersConstant.full_discount,
          'type': OffersConstant.order_offers,
          'supportQrcode': 0,
        },
      };

      setDateTimeForHttpData(data);

      var result = await api.addFullDiscount(data);

      if (!result.successful()) {
        toast(result.msg);
        return false;
      }
      toast('添加成功');
      return true;
    } catch (e) {
      toast(e.toString());
      return false;
    } finally {
      hideLoadingToast();
    }
  }
}
